<template>
  <div class="content-wrap" id="menu-container" v-loading="loading">
    <!-- 检索区域 -->
    <el-form class="search-wrap" :inline="true" :model="searchForm">
      <!-- 模糊查找 -->
      <el-form-item class="search-wrap-item" label="需求关键字：">
        <el-autocomplete style="width: 400px;" v-model="searchForm.title_name" :fetch-suggestions="querySearch"
          clearable class="inline-input search-select" placeholder="请输入需求名称" @select="handleSearch"
          @clear="handleSearch" />
      </el-form-item>
      <!-- 测试人员 -->
      <el-form-item class="search-wrap-item" label="测试人员：">
        <el-select class="search-select" filterable v-model="searchForm.case_names" placeholder="全部" size="default"
          multiple clearable style="min-width: 200px; max-height: 50px; font-weight: normal;" @change="handleSearch"
          @clear="handleSearch" @remove-tag="handleSearch">
          <el-option v-for="(item, index) in allCaseNameList" :key="item.uuid" :lable="item.nickName"
            :value="item.nickName"></el-option>
        </el-select>
      </el-form-item>
      <!-- 流转时间 -->
      <el-form-item class="search-wrap-item" label="流转时间：">
        <el-date-picker style="width: 240px" v-model="searchForm.timeFrame" type="daterange" unlink-panels
          range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" format="YYYY/MM/DD"
          value-format="YYYY-MM-DD" @change="handleSearch" />
      </el-form-item>
      <el-form-item style="font-size: 12px; margin: 10px 0;">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 各需求BUG列表 -->
    <el-card class="card-wrap" v-loading="loading">
      <div class="card-wrap-table">
        <el-table :data="allRequirementBugs" style="width: 100%" :header-cell-style="tableHeaderStyle"
          :max-height="'660px'">
          <el-table-column show-overflow-tooltip prop="requirementName" label="需求名称" />
          <el-table-column prop="trueTestName" label="测试姓名" width="100" align="center" />
          <el-table-column prop="address" label="BUG数量" width="160" align="center">
            <template #="{ row }">
              {{ handleMathStatus(row).total }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="修复进度" width="280" align="center">
            <template #="{ row }">
              <el-progress v-if="handleMathStatus(row).percentage == 0" :percentage="handleMathStatus(row).percentage"
                status="exception" stroke-width="7" />
              <el-progress v-else-if="handleMathStatus(row).percentage == 100"
                :percentage="handleMathStatus(row).percentage" status="success" stroke-width="7" />
              <el-progress v-else :percentage="handleMathStatus(row).percentage" :color="customColors"
                stroke-width="7" />
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" align="center" width="200">
            <template #="{ row }">
              <!-- 查看需求 -->
              <el-tooltip content="查看需求" placement="bottom" effect="light">
                <el-button plain size="small" @click="handleViewRequire(row.ID)">查看
                </el-button>
              </el-tooltip>
              <!-- 添加bug -->
              <el-tooltip content="新增Bug" placement="bottom" effect="light">
                <el-button class="add-bug-btn" type="success" @click="handleAddBug(row.ID)" size="small" plain>新增
                </el-button>
              </el-tooltip>
              <!-- bug列表 -->
              <el-tooltip content="Bug列表" placement="bottom" effect="light">
                <el-button class="add-bug-btn" type="primary" :disabled="!(handleMathStatus(row).total > 0)"
                  @click="handleBugList(row.ID)" size="small" plain>详情
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <div class="page-wrap">
        <Pagination v-model:currten-page="pageInfo.page" :page-size="pageInfo.pageSize" :total="pageInfo.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </Pagination>
      </div>
    </el-card>

    <!-- 添加BUG弹窗 -->
    <el-dialog id="dialogAddBugForm" v-model="dialogAddBugVisible" title="添加Bug" width="960px"
      style="width: 960px; margin: 50px auto;" :show-close="true">
      <AddRequirementBugVue :visible="dialogAddBugVisible" :id="isRequirementID" @submit-success="handleSubmitSuccess">
      </AddRequirementBugVue>
    </el-dialog>

    <!-- 需求详情弹窗 -->
    <el-dialog v-if="dialogInfoVisible" style="width: 1200px" :close-on-click-modal="false" v-model="dialogInfoVisible"
      @close="dialogInfoVisible = false" @closed="dialogInfoVisible = false" top="8vh">
      <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="!dialogInfoVisible" :isComment="true">
      </CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import AddRequirementBugVue from "@/components/requirement/addRequirementBug.vue";
import CommonRequirementInfoVue from "@/components/requirement/comomRequirementInfo.vue";
import { onMounted, reactive, ref } from "vue";
import Pagination from "@/components/Pagenation/index.vue";
import { postRequirementsBugs } from "@/api/bug/index"; // 引入接口函数
import { ElMessage } from "element-plus";
import { getShortCuts } from "@/utils/utils"; //引入公共函数
import type { BugList } from "@/api/bug/type";
import useCommonDataStore from "@/store/common/common"; //获取所有的修复人
import { useRouter } from "vue-router";


const router = useRouter();
const useCommonStore = useCommonDataStore();
const loading = ref(false);

const isRequirementID = ref<any>(null);
const dialogInfoVisible = ref(false); //查看需求弹窗控件

// 自定义进度条的颜色
const customColors = [
  { color: "#F56C6C", percentage: 40 },
  { color: "#409EFF", percentage: 60 },
  { color: "#1989fa", percentage: 80 },
  { color: "#67C23A", percentage: 100 },
];
// 自定义table样式
const tableHeaderStyle = {
  backgroundColor: "#F2F6FC",
  color: "#909399",
  textAlign: "center",
};
// 初始分页
const pageInfo = reactive({
  total: 0, //总条目
  page: 1, //当前页码
  pageSize: 20, //当前每页条数
});

// 定义所有的bug数据
const allRequirementBugs = ref([] as BugList[]);
// 定义检索区域下拉列表数据
const allCaseNameList = ref<any>([]);
const allRequirementList = ref<any>([]);
// 定义添加bug弹窗控件
const dialogAddBugVisible = ref(false);
// 定义所有的修复人员列表
const allRoleUserList = ref<any>([]);


// 初始化查询参数的方法
const initSearchFrom = () => ({
  title_name: "",
  case_names: [],
  timeFrame: null,
  page: 1,
  page_size: 20,
});

// 定义查询参数初始值
const searchForm = reactive(initSearchFrom());

// 获取公共数据
const getCommon = async (index: any) => {
  await useCommonStore.getAllRoleUsersList(index);
  allRoleUserList.value = useCommonStore.$state.allRoleUserList;

  allCaseNameList.value = allRoleUserList.value.filter((item: any) => item.authorityId == 666);

};

// TODO 获取检索区域下拉列表数据：allRequirementList
const getAllCaseNameList = async () => {
  loading.value = true;
  const { data } = await postRequirementsBugs({
    title_name: "",
    case_names: [],
    begin_time: null,
    end_time: null,
    page: 1,
    page_size: 10000,
  });

  if (data.code === 200) {
    // 用于模糊查找数据
    allRequirementList.value = data.data.list.map(
      (item) => item.requirementName
    );
  } else {
    ElMessage.error(data.msg);
  }
  loading.value = false;
};

// TODO 模糊查询的方法
const querySearch = (queryString: string, cb: any) => {
  const results = allRequirementList.value
    .filter((item: any) => item.includes(queryString))
    .map((item: any) => ({ value: item }));
  cb(results);
};

// TODO 获取所有需求下的所有BUG
const getAllBugs = async () => {
  loading.value = true;

  const { data } = await postRequirementsBugs({
    title_name: searchForm.title_name,
    case_names: searchForm.case_names,
    begin_time: searchForm.timeFrame !== null ? searchForm.timeFrame[0] : null,
    end_time: searchForm.timeFrame !== null ? searchForm.timeFrame[1] : null,
    page: pageInfo.page,
    page_size: pageInfo.pageSize,
  });

  if (data.code === 200) {
    // 存储响应数据
    allRequirementBugs.value = data.data.list;
    pageInfo.page = data.data.page;
    pageInfo.pageSize = data.data.pageSize;
    pageInfo.total = data.data.total;
  } else {
    ElMessage.error(data.msg);
    throw console.error(data.msg);
  }
  loading.value = false;
};

// TODO 计算进度条及bug数量
const handleMathStatus = (item: any) => {
  const total = item.bugStatus1 + item.bugStatus2 + item.bugStatus3 + item.bugStatus4 + item.bugStatus5 + item.bugStatus6 + item.bugStatus7;
  if (total !== 0) {
    const percentage = (((item.bugStatus6 + item.bugStatus7) / total) * 100).toFixed(0);
    return {
      total,
      percentage
    }
  } else {
    const percentage = 0;
    return {
      total,
      percentage
    }
  }
}

// TODO 查询事件
// 时间快捷选择器
const shortcuts = getShortCuts();

// 搜索功能
const handleSearch = async () => {
  loading.value = true;
  await getAllBugs();
  loading.value = false;
};

// TODO 点击【BUG数量】跳转到对应的BUG列表页
const handleBugList = (id: number) => {
  router.push({
    name: "BugsList",
    params: { id },
  });
};

// 更改每页条目数
const handleSizeChange = async (val: number) => {
  pageInfo.pageSize = val;
  pageInfo.page = 1;
  await getAllBugs();
};
// 更改当前页码
const handleCurrentChange = async (val: number) => {
  pageInfo.page = val;
  await getAllBugs();
};

//TODO 添加BUG
// 点击【添加BUG】，开启弹窗
const handleAddBug = async (id: number) => {
  dialogAddBugVisible.value = true;
  isRequirementID.value = id;
};

// TODO 子组件添加Bug结果
const handleSubmitSuccess = async (success: boolean) => {
  if (success) {
    dialogAddBugVisible.value = false;
    loading.value = true;
    await getAllCaseNameList();
    await getAllBugs()
    loading.value = false;
  } else {
    dialogAddBugVisible.value = false;
    return;
  }
};

//* 查看需求功能
const handleViewRequire = async (index: number) => {
  dialogInfoVisible.value = true;
  isRequirementID.value = index;
};

onMounted(async () => {
  getAllCaseNameList();
  getAllBugs();
  getCommon("");
  // getCommon(666);
});
</script>

<style lang="scss" scoped>
.el-select__selection {
  flex-wrap: nowrap;
  overflow-y: scroll;
}

/* 需求名称溢出 */
.requirement-title {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

/* bug数量 */
.bug-number {
  cursor: pointer;
  color: #409eff;
}

.search-wrap {
  padding: 0 10px !important;
}

.search-wrap-item {
  margin-bottom: 0 !important;
}

// 添加bug弹窗
.dialog-form-box {
  width: 100%;
  height: 720px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;

  .dialog-form-item-icon svg {
    margin-top: 15px;
  }

  .dialog-form-item-box {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;


    // bug等级按钮
    .bug-level-0 {
      --el-radio-button-checked-bg-color: #B40404;
      --el-radio-button-checked-border-color: #B40404;
      list-style: none;
      border: 1px solid #dcdcdc;
      border-radius: 5px 0 0 5px;
    }

    .bug-level-1 {
      list-style: none;
      border: 1px solid #dcdcdc;
      --el-radio-button-checked-bg-color: #ff0000;
      --el-radio-button-checked-border-color: #ff0000;
    }

    .bug-level-2 {
      list-style: none;
      border: 1px solid #dcdcdc;
      --el-radio-button-checked-bg-color: #67c23a;
      --el-radio-button-checked-border-color: #67c23a;
    }

    .bug-level-3 {
      list-style: none;
      border: 1px solid #dcdcdc;
      border-radius: 0 5px 5px 0;
    }

    // bug编辑区域
    .bug-edit-box {
      width: 100%;
      height: 510px;
      border-top: 1px solid #ddd;
      box-shadow: none;
      border-radius: 0;
      padding: 10px 20px;
    }
  }

  // 添加bug操作区域
  .bug-edit-btn {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-right: 20px;
  }
}

;
</style>
